<template>
	<div>
		<Tabs>
			<TabPane label="基本信息"></TabPane>
		</Tabs>
		
		<div>
			<div class="ui-tab-navs">
				<a
					class="ui-tab-navs-cell"
					href="javascript:;"
					v-for="item in goodsTypes"
					:class="{active: formData.type == item.type, disabled: formData.id && formData.type != item.type}"
					@click="handleChangeGoodsType(item)"
				>
					<p class="title">{{ item.title }} </p>
					<p class="desc">（{{ item.desc }}）</p>
				</a>
			</div>
			<p style="margin-top: 15px;">注意：一旦选择商品类型并新增商品成功后，商品类型不可变</p>
			<Divider />
		</div>
		
		<Form ref="form" :model="formData" :rules="rules" label-position="top">
			<!-- 海淘商品暂不支持导入 -->
			<!--<template v-if="formData.type != 1">
				<FormDescItem label="商品导入" desc="目前仅支持淘宝、天猫和京东的商品导入">
					<Input>
						<span slot="prepend">https://</span>
	        			<Button slot="append">导入</Button>
					</Input>
				</FormDescItem>
			</template>-->
			<FormDescItem label="商品名称" prop="name" desc="商品名称不能为空，最长不能超过200个字符">
				<Input v-model="formData.name" />
			</FormDescItem>
			<FormDescItem label="商品副标题" prop="subtitle" desc="商品副标题是用于介绍商品的描述信息，此类目选填">
				<Input v-model="formData.subtitle" />
			</FormDescItem>
			<FormDescItem label="商品品牌" prop="brand_id">
				<SelectBrand v-model="formData.brand_id" />
	            <p slot="desc">为商品选择所属品牌，便于用户按照品牌进行查找，需要先 <a href="/#/goods/brand/edit">新增品牌</a></p>
			</FormDescItem>
			<FormDescItem label="库存单位" desc="选为商品设置库存单位，库存单位主要用于前台展示和后台标记，此类目选填">
				<Select>
	                <Option value="1">斤</Option>
	                <Option value="4">件</Option>
	                <Option value="2">kg</Option>
	                <Option value="3">g</Option>
	            </Select>
			</FormDescItem>
			<FormDescItem label="商品分类" prop="catid">
				<SelectCategory v-model="formData.catid" />
	            <p slot="desc">选择商品所属分类，一个商品只能属于一个分类，需要先 <a href="/#/goods/classify/edit">新增分类</a></p>
			</FormDescItem>
			
			<Tabs>
				<TabPane label="媒体图片">
					
				</TabPane>
			</Tabs>
			<FormDescItem label="商品图片" prop="siteName" desc="商品默认图片最多上传5张图片，上传后可点击查看大图，建议尺寸为：800px × 800px">
				<div style="font-size: 0;">
					<ImageCells :value="formData.imgs" :width="50" preview remove></ImageCells>
					<SelectImage v-if="formData.imgs.length < 5" @click="showMaterialLibrary = true" />
				</div>
			</FormDescItem>
			<FormDescItem label="商品视频" prop="siteName" desc="商品视频最多可以上传一个，如上传图片，默认播放视频，建议时长9-30秒，建议视频宽高比1:1">
				<div>
					<SelectImage />
				</div>
			</FormDescItem>
			
			<Tabs>
				<TabPane label="规格属性"></TabPane>
			</Tabs>
			<FormDescItem label="商品规格" desc="选择是否开启多规格">
				<RadioGroup v-model="formData.spec_type">
	                <Radio :label="1">统一规格</Radio>
	                <Radio :label="2">多规格</Radio>
	            </RadioGroup>
			</FormDescItem>
			<!-- 统一规格 -->
			<template v-if="formData.spec_type == 1">
				<FormDescItem label="商品销售价" desc="设置商品销售价格">
					<div>
						<InputAmount v-model="formData.shop_price" />
					</div>
				</FormDescItem>
				<FormDescItem label="商品成本价" desc="设置商品成本价格，成本价填写可以统计商品毛利">
					<div>
						<InputAmount v-model="formData.purchasing_price" />
					</div>
				</FormDescItem>
				<FormDescItem label="商品货号" desc="设置商品的货号">
					<Input v-model="formData.sn" />
				</FormDescItem>
				<FormDescItem label="商品条码" desc="设置商品的条码">
					<Input />
				</FormDescItem>
				<FormDescItem label="商品重量" desc="设置商品重量，该重量用于运费模版中的计重收费和同城配送续重收费。">
					<Input v-model="formData.unit_value">
						<span slot="append">公斤(kg)</span>
					</Input>
				</FormDescItem>
				<FormDescItem label="商品库存" prop="number" desc="设置商品的库存数量，如商品不限制库存，可以勾选不限库存，则商品不会售罄">
					<Input v-model="formData.number" number :disabled="formData.sku_total_type ? true : false">
						<template slot="append">
							<Checkbox label="不限库存" v-model="formData.sku_total_type" :true-value="1" :false-value="0">不限库存</Checkbox>
						</template>
					</Input>
				</FormDescItem>
			</template>
			<!-- 多规格 -->
			<template v-if="formData.spec_type == 2">
				<GoodsSpecs ref="specs" style="margin-bottom: 15px;"></GoodsSpecs>
			</template>
			
			<Tabs>
				<TabPane label="其他信息"></TabPane>
			</Tabs>
			<ui-box solid :radius="false">
				<Row :gutter="20">
					<Col span="6">
						<FormItem label="商品产地">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
					<Col span="6">
						<FormItem label="进口/国产">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
					<Col span="6">
						<FormItem label="适用年龄(多选)">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
					<Col span="6">
						<FormItem label="保质期">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
				</Row>
				<Row :gutter="20">
					<Col span="6">
						<FormItem label="包装">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
					<Col span="6">
						<FormItem label="奶源地">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
					<Col span="6">
						<FormItem label="净含量(多选)">
							<Select>
				                <Option value="1">分组1</Option>
				            </Select>
						</FormItem>
					</Col>
					<Col span="6">
						<FormItem label="商品毛重">
							<InputNumber style="width: 100%;"></InputNumber>
						</FormItem>
					</Col>
				</Row>
			</ui-box>
			
			<Tabs>
				<TabPane label="其他信息"></TabPane>
			</Tabs>
			<FormDescItem label="上架状态" desc="如选择审核不上架，当商品审核通过后，商品将放入商品仓库中">
				<RadioGroup v-model="formData.status">
	                <Radio :label="1">审核上架</Radio>
	                <Radio :label="0">审核不上架</Radio>
	            </RadioGroup>
			</FormDescItem>
			<FormDescItem label="库存警告" desc="填写商品库存警告数，当库存小于等于库存警告数时会给与提醒">
				<InputNumber v-model="formData.warn_number" :min="0" :precision="0" />
			</FormDescItem>
			<FormDescItem label="销售渠道" desc="请选择该商品允许销售的渠道，必须选择其中一个">
	            <CheckboxGroup>
			        <Checkbox :label="1">线下门店销售</Checkbox>
			        <Checkbox :label="2">线上电商销售</Checkbox>
			    </CheckboxGroup>
			</FormDescItem>
			<FormDescItem label="商品分组" desc="为商品选择分组，可在营销中按照商品分组做相关活动，可多选">
				<Select>
	                <Option value="1">分组1</Option>
	            </Select>
			</FormDescItem>
			<!-- 仅海淘商品显示 -->
			<template v-if="formData.type == 1">
				<FormDescItem label="商品税率" prop="rate" desc="填写商品综合税率，设置后商品下单时需缴纳商品进口税，如设置为包税则不需要缴纳进口税，税率为百分比">
					<Input v-model="formData.rate" number :disabled="formData.is_free_rate ? true : false">
						<template slot="append">
							<Checkbox label="包税" v-model="formData.is_free_rate" :true-value="1" :false-value="0">包税</Checkbox>
						</template>
					</Input>
				</FormDescItem>
				<FormDescItem label="商品国家" desc="选择商品所属来源国家，所选国家会展示给客户查看">
					<Select v-model="formData.country">
		                <Option v-for="item in countries" :key="item.id" :value="item.id">{{ item.name }}</Option>
		            </Select>
				</FormDescItem>
				<FormDescItem label="商品出库" desc="选择商品所属国内保税仓，所选出库保税仓会展示给客户查看">
					<Select v-model="formData.stock">
		                <Option v-for="item in bondedWarehouses" :key="item.id" :value="item.id">{{ item.name }}</Option>
		            </Select>
				</FormDescItem>
			</template>
			<FormDescItem label="首选供应商">
				<Select>
	                <Option value="1">供应商1</Option>
	            </Select>
			</FormDescItem>
			<Button type="dashed" icon="ios-add">添加一个供应商</Button>
			
			<Tabs>
				<TabPane label="网店设置"></TabPane>
			</Tabs>
			<FormDescItem label="商品分享描述" desc="微信分享给好友时会显示，建议36个字以内">
				<Input v-model="formData.share_description" />
			</FormDescItem>
			<FormDescItem desc="如商品支持多种配送方式，可多选，运费模板支持按地区设置运费，按购买件数计算运费，按重量计算运费等">
				<CheckboxGroup v-model="formData.delivery_type">
			        <Checkbox :label="1">快递发货</Checkbox>
			        <Checkbox :label="2">同城配送</Checkbox>
			        <Checkbox :label="3">到店自提</Checkbox>
			    </CheckboxGroup>
				<Select v-model="formData.delivery_template_id">
	                <Option v-for="item in deliveryTemplates" :key="item.id" :value="item.id">{{ item.name }}</Option>
	            </Select>
			</FormDescItem>
			<FormDescItem label="商品限购" prop="purchase_num" desc="设置每个用户最多可购买多少件商品，如商品为多规格，则针对每一个规格进行商品限购">
				<Input v-model="formData.purchase_num" number :disabled="formData.purchase_type ? true : false">
					<template slot="append">
						<Checkbox label="不限购" v-model="formData.purchase_type" :true-value="1" :false-value="0">不限购</Checkbox>
					</template>
				</Input>
			</FormDescItem>
			<!--<FormDescItem label="商品标签" desc="为商品打上标签，可在营销中按照标签分组做相关活动">
				<InputTags v-model="formData.tags" :color="['primary', 'success', 'error']" />
			</FormDescItem>-->
			<FormDescItem label="商品关键词(SEO)" desc="Keywords项出现在页面头部的标签中，用于记录本页面的关键字，多个关键字请用分隔符分隔，主要针对H5版本">
				<InputTags v-model="formData.keyword" color="primary" />
			</FormDescItem>
			<FormDescItem label="商品描述(SEO)" desc="Description出现在页面头部的Meta标签中，用于记录本页面的摘要与描述，建议不超过80个字，主要针对H5版本">
				<Input v-model="formData.description" type="textarea" :rows="5" />
			</FormDescItem>
		</Form>
		
		<Tabs>
			<TabPane label="详情描述"></TabPane>
		</Tabs>
		<!--富文本编辑-->
    	<UEditor ref="ueditor"></UEditor>
    	
		<FooterBar>
			<div style="text-align: center;">
				<Button @click="handleBack">返回列表</Button>
				<Button type="primary" @click="handleSubmit" :loading="commiting">保存设置</Button>
			</div>
		</FooterBar>
		
		<MaterialLibrary v-model="showMaterialLibrary" :max="5" @change="handleSelectImage"></MaterialLibrary>
		
		<LoadingMask v-if="isLoading"></LoadingMask>
	</div>
</template>

<script>
import Util from '@/libs/util.js';
import UEditor from '@/components/UEditor.vue';
import SelectImage from '@/components/SelectImage.vue';
import ImageCells from '@/components/ImageCell/cells.vue';
import FooterBar from '@/components/FooterBar.vue';
import MaterialLibrary from '@/components/MaterialLibrary.vue';
import GoodsSpecs from './components/GoodsSpecs.vue';
import LoadingMask from '@/components/LoadingMask.vue';

import FormDescItem from '@/components/form/FormDescItem.vue';
import InputTags from '@/components/form/InputTags.vue';
import InputAmount from '@/components/form/InputAmount.vue';
import SelectBrand from '@/components/form/SelectBrand.vue';
import SelectCategory from '@/components/form/SelectCategory.vue';
export default {
	name: 'goodsEdit',
	components: {
		UEditor,
		SelectImage,
		ImageCells,
		FooterBar,
		InputTags,
		InputAmount,
		FormDescItem,
		MaterialLibrary,
		GoodsSpecs,
		LoadingMask,
		SelectBrand,
		SelectCategory
	},
	data() {
		return {
			isLoading: false,
			commiting: false,
			showMaterialLibrary: false,
			// 保税仓
			bondedWarehouses: [],
			formData: {
				id: '',
				type: 0,
				name: '',
				share_description: '',
				subtitle: '',
				catid: [],
				brand_id: null,
				imgs: [],
				video: '',
				spec_type: 1,
				shop_price: 0,
				purchasing_price: 0,
				number: 9999,
				sku_total_type: 0,
				unit_value: null,
				unit_type: 1,
				sn: '',
				status: 1,
				warn_number: 5,
				delivery_type: [],
				delivery_template_id: 0,
				purchase_type: 1,
				purchase_num: 5,
				rate: 0,
				is_free_rate: 0,
				country: '',
				stock: '',
				tags: [],
				keyword: [],
				description: ''
			},
			rules: {
				name: [
					{required: true, message: "请填写商品名称", trigger: "blur"}
				],
				catid: [
					{required: true, type: 'array', message: "请选择商品所属分类", trigger: "change"}
				],
				brand_id: [
					{required: true, type: 'number', message: "请选择商品所属品牌", trigger: "change"}
				],
				number: [
					{type: 'number', message: "请输入数字类型", trigger: "blur"}
				],
				purchase_num: [
					{type: 'number', message: "请输入数字类型", trigger: "blur"}
				],
				rate: [
					{type: 'number', message: "请输入数字类型", trigger: "blur"}
				]
			},
			goodsTypes: [
				{
					type: 0,
					title: '普通商品',
					desc: '普通实物商品'
				},
				{
					type: 1,
					title: '海淘商品',
					desc: '需验证身份证'
				}
			]
		}
	},
	computed: {
		brands() {
        	return this.$store.state.app.brands;
        },
        categories() {
        	return this.$store.state.app.categories;
        },
        deliveryTemplates() {
        	return this.$store.state.app.deliveryTemplates;
        },
        countries() {
        	return this.$store.state.app.countries;
        },
	},
	mounted() {
		// 获取运费模板
    	this.$store.dispatch('getDeliveryTemplates');
    	// 获取国家列表
    	this.$store.dispatch('getCountryData');
		this.init();
	},
	methods: {
		init() {
			// 获取保税仓列表
			Util.ajax.post(this.API['API_SETTING_BONDED_WAREHOUSE'], {}).then((res) => {
				this.bondedWarehouses = res;
			}).catch(() => {
				
			})
			
			// 获取商品详情
			if(this.$route.query.id) {
				this.isLoading = true;
				this.formData.id = this.$route.query.id;
				Util.ajax.post(this.API['API_GOODS_DETAIL'], {id: this.formData.id, relations: ['category']}).then((res) => {
					// 基本数据
					this.formData.type = res.type;
					this.formData.name = res.name;
					this.formData.share_description = res.share_description;
					this.formData.subtitle = res.subtitle;
					this.formData.imgs = res.imgs || [];
					this.formData.brand_id = res.brand_id;
					this.formData.video = res.video;
					this.formData.status = res.status;
					this.formData.delivery_template_id = res.delivery_template_id;
					this.formData.warn_number = res.warn_number;
					this.formData.purchase_type = res.purchase_type;
					this.formData.purchase_num = res.purchase_num;
					this.formData.description = res.description;
					if(res.category_text && res.category_text.id) {
						this.formData.catid = res.category_text.id.split('>').map(item => {
							return Number(item);
						})
					}
					if(res.delivery_type) {
						this.formData.delivery_type = res.delivery_type.split(',').map(item => {
							return Number(item);
						});
					}
					if(res.tags) {
						this.formData.tags = res.tags.split(',')
					}
					if(res.keyword) {
						this.formData.keyword = res.keyword.split(',')
					}
					// 编辑器
					this.$refs.ueditor.init(res.content)
					
					// 规格
					this.formData.spec_type = res.spec_type;
					if(res.spec_type == 1) {
						// 统一规格
						this.formData.shop_price = Number(res.specs.shop_price);
						this.formData.purchasing_price = Number(res.specs.purchasing_price);
						this.formData.number = Number(res.specs.number);
						this.formData.sku_total_type = res.sku_total_type;
						this.formData.unit_type = res.unit_type;
						this.formData.unit_value = res.unit_value;
						this.formData.sn = res.specs.sn;
					}else{
						// 多规格
						let specs = res.specs.map((item, index) => {
							let obj = {
								name: item.name,
								value: item.value.map(val => {
									return val.name;
								})
							}
							if(index == 0) {
								obj.imgs = item.value.map(val => {
									return val.img || '';
								})
							}
							return obj;
						})
						let skus = res.sku_info.map(item => {
							let names = item.spec.map(spec => {
								return spec.value;
							})
							return {
								sku_name: names.join(' '),
								shop_price: Number(item.shop_price),
								purchasing_price: Number(item.purchasing_price),
								number: item.number,
								weight: Number(item.weight),
								sn: item.sn,
								if_show: item.if_show,
								is_lock: item.is_lock,
								spec: item.spec
							}
						})
						this.$nextTick(() => {
							this.$refs.specs.isConfirm = true;
							this.$refs.specs.spec_is_show = res.spec_is_show;
							this.$refs.specs.img_is_show = res.img_is_show;
							this.$refs.specs.specs = specs;
							this.$refs.specs.skus = skus;
						})
					}
					
					// 海淘
					if(res.type == 1) {
						this.formData.rate = res.rate;
						this.formData.is_free_rate = res.is_free_rate;
						this.formData.country = res.country_id;
						this.formData.stock = res.stock_id;
					}
					
					this.isLoading = false;
				}).catch(() => {
					
				})
			}else{
				this.$refs.ueditor.init();
			}
		},
		// 切换商品类型
		handleChangeGoodsType(item) {
			// 商品编辑不能切换商品类型
			if(this.formData.id) {
				return false;
			}
			this.formData.type = item.type;
		},
		// 选择的图片
		handleSelectImage(images) {
			this.formData.imgs = images.map(item => {
				return item.url;
			});
		},
		// 提交表单
		handleSubmit() {
			if(this.commiting) return false;
			this.$refs.form.validate(valid =>{
				if(valid) {
					let form = this.formData;
					// 预设通用数据
					let params = {
						goods: {
							type: form.type,
							name: form.name,
							share_description: form.share_description,
							subtitle: form.subtitle,
							catid: form.catid[form.catid.length - 1],
							brand_id: form.brand_id,
							imgs: form.imgs,
							video: form.video,
							spec_type: form.spec_type,
							status: form.status,
							delivery_type: form.delivery_type.join(','),
							delivery_template_id: form.delivery_template_id,
							warn_number: form.warn_number,
							purchase_type: form.purchase_type,
							purchase_num: form.purchase_num,
							tags: form.tags.join(','),
							keyword: form.keyword.join(','),
							description: form.description,
							content: this.$refs.ueditor.getUEContent()
						}
					}
					// 单规格和多规格的处理
					if(form.spec_type == 1) {
						// 统一规格
						params.goods.unit_type = form.unit_type;
						params.goods.unit_value = form.unit_value;
						params.spec = {
							shop_price: form.shop_price,
							purchasing_price: form.purchasing_price,
							number: form.number,
							sku_total_type: form.sku_total_type,
							sn: form.sn
						}
					}else{
						let specGroups = this.$refs.specs.getData();
						// 多规格
						params.spec = specGroups.spec;
						params.skus = specGroups.skus;
						params.goods.img_is_show = specGroups.img_is_show;
						params.goods.spec_is_show = specGroups.spec_is_show;
					}
					
					// 海淘商品
					if(form.type == 1) {
						params.goods.rate = form.rate;
						params.goods.country = form.country;
						params.goods.stock = form.stock;
					}
					
					this.commiting = true;
					if(form.id) {
						params.goods.id = form.id;
						// 编辑
						Util.ajax.post(this.API['API_GOODS_SAVE'], params).then((res) => {
							this.$Message.success({
								content: '商品编辑成功',
								onClose: () => {
									this.handleBack();
								}
							})
						}).catch(() => {
							this.commiting = false;
						})
					}else{
						// 新增
						Util.ajax.post(this.API['API_GOODS_CREATE'], params).then((res) => {
							this.$Message.success({
								content: '商品添加成功',
								onClose: () => {
									this.handleBack();
								}
							})
						}).catch(() => {
							this.commiting = false;
						})
					}
				}
			})
		},
		// 返回列表
		handleBack() {
			this.$router.back();
		}
	}
}
</script>